<template>
  <div>
    <query-form
      v-model:queryField="queryField"
      :fieldList="qFieldList"
      @search="handleSearchQuery"
      @reset="restQuery"
    />
    <table-list
      v-model:page-params="pageParams"
      :loading="loading"
      :list="list"
      :field="tableField"
      :total="total"
      :permission-prefix="permissionPrefix"
      :get-list="getList"
      :handle-selection-change="handleSelectionChange"
      :handle-delete="handleDelete"
      :handle-update="handleUpdate"
      :handle-detail="handleDetail"
    />

    <add-update-dialog
      v-model="open"
      v-model:form="form"
      :isDetail="isDetail"
      :title="title"
      :submit-form="submitForm"
      :cancel="cancel"
      :field="formField"
    />
    <!-- <upload-dialog
      ref="uploadRef"
      :import-data="handleImportData"
      :handle-download-tpl="handleDownloadTpl"
      @success="handleQuery"
    /> -->
  </div>
</template>
<script setup>
  import { ref, computed, watch } from 'vue';
  import TableList from '@/views/web/bu/curd/components/table-list';
  import AddUpdateDialog from '@/views/web/bu/curd/components/add-update-dialog';
  import queryForm from './query-form.vue';
  import modal from '@/plugins/modal';

  import {
    pageSdkDqSingleCurd,
    getSdkDqSingleCurdInfo,
    addSdkDqSingleCurd,
    updateSdkDqSingleCurd,
    delSdkDqSingleCurd,
    // exportSdkDqSingleCurd,
  } from '@/api/web/db/dataquery/sdkDqSingleCurd';
  import { listSdkDqDsTbCl } from '@/api/web/db/dataquery/sdkDqDsTbCl';
  import { selectDictLabels } from '@/utils/base';
  import { getDicts } from '@/api/system/dict/data';

  const props = defineProps({
    selectPNode: {
      type: Object,
      default: () => ({}),
    },
  });

  // 分页参数
  const pageParams = ref({ pageNum: 1, pageSize: 10 });
  // 搜索项 和 搜索参数
  const queryField = ref([]);
  const queryParams = ref({});
  // 表单项 和 表单参数
  const formField = ref([]);
  const formParams = ref({});
  const loading = ref(false);
  // const queryRef = ref(null);
  const permissionPrefix = ref(null);
  const list = ref([]);
  const open = ref(false);
  const isDetail = ref(false);
  // 新增 修改 表单
  const form = ref({});
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref('');

  const qFieldList = ref([]);

  // 列表项
  const tableField = ref([]);
  const dicts = ref({});
  const primaryKey = ref(null);
  const multiOptControlType = ['select', 'radio', 'checkbox'];
  const reMap = new Map([
    ['邮件', /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/],
    ['手机号', /^[1][3,4,5,7,8][0-9]{9}$/],
    ['身份证号', /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/],
    ['港澳通行证', /^[HMhm]{1}([0-9]{10}|[0-9]{8})$/],
    ['字母', /^[0-9]+$/],
    ['数字', /^[a-zA-Z]+$/],
  ]);
  const formatMap = new Map([
    ['yyyy-MM-dd', 'YYYY-MM-DD'],
    ['yyyy/MM/dd', 'YYYY/MM/DD'],
    ['yyyy年MM月dd日', 'YYYY年MM月DD日'],
    ['HH:mm', 'HH:mm'],
    ['HH:mm:ss', 'HH:mm:ss'],
    ['yyyy-MM-dd HH:mm:ss', 'YYYY-MM-DD HH:mm:ss'],
    ['yyyy/MM/dd HH:mm:ss', 'YYYY/MM/DD HH:mm:ss'],
    ['yyyy年MM月dd日 HH时mm分ss秒', 'YYYY年MM月DD日 HH时mm分ss秒'],
  ]);
  const getList = ref(null);
  const cancel = ref(null);
  const reset = ref(null);
  const handleQuery = ref(null);
  const handleAdd = ref(null);
  const handleUpdate = ref(null);
  const handleDetail = ref(null);
  const submitForm = ref(null);
  const handleDelete = ref(null);
  // const handleDownloadTpl = ref(null);
  // const handleExport = ref(null);
  // const handleImportData = ref(null);

  const tbid = computed(() => {
    return props.selectPNode.id;
  });
  watch(
    () => props.selectPNode,
    (pnode) => {
      if (pnode) {
        // queryParams.value.cateId = pnode.id;
        // getList();
        getColData();
      }
    },
    { immediate: true },
  );

  function restQuery() {
    queryField.value = [];
    pageParams.value.pageNum = 1;
    getList.value();
  }

  function handleSearchQuery(params) {
    console.log({ params });
    queryParams.value = params;
    handleQuery.value();
  }

  function genFormField(formCols) {
    console.log({ formCols });
    formField.value = formCols.map((k) => ({
      type:
        k.inputType === 'DatetimePicker'
          ? 'DatePicker'
          : k.inputType === 'password' || k.inputType === 'textarea'
            ? 'input'
            : k.inputType,
      title: k.comment,
      field: k.name,
      hidden: !k.defaultShow,
      props: {
        placeholder: k.fieldRemark || `请${k.inputType === 'select' ? '选择' : '输入'}${k.comment}`,
        clearable: true,
        filterable: true,
        multiple: k.queryCondition === 'in',
        valueFormat: formatMap.get(k.format) || k.format || '',
        'show-password': k.inputType === 'password',
        type:
          k.inputType === 'DatetimePicker'
            ? `datetime${k.queryCondition === 'range' ? '' : ''}`
            : k.inputType === 'DatePicker'
              ? `date${k.queryCondition === 'range' ? '' : ''}`
              : k.inputType === 'password'
                ? 'password'
                : k.inputType === 'textarea'
                  ? 'textarea'
                  : null,
        isRange: k.inputType === 'TimePicker' && k.queryCondition === 'range',
      },
      validate: [{ required: !k.ableBeNull, message: `${k.comment}不能为空`, trigger: 'blur' }]
        .concat(
          k.validator
            ? {
                pattern: reMap.get(k.validator) || /.*/,
                message: `${k.validator}格式不正确`,
              }
            : [],
        )
        .concat(
          k.regexpStr
            ? {
                pattern: new RegExp((k.regexpStr || '').replace(/(^\/|\/$)/g, '')),
                message: '格式不正确',
              }
            : [],
        ),
      ext: k,
      ...(multiOptControlType.includes(k.inputType)
        ? {
            options: k.dictType ? dicts.value[k.dictType] : [],
          }
        : {}),
      ...(k.relationDictType === '行政区划'
        ? {
            emit: ['focus'],
            emitPrefix: k.name.replace('_', '').toLowerCase(),
          }
        : {}),
    }));
    formParams.value = formField.value.reduce((prev, curr) => {
      prev[curr.field] = curr.ext.inputType === 'checkbox' ? [] : curr.ext.fieldDefault || null;
      return prev;
    }, {});
    console.log({ formField: formField.value, formParams: formParams.value });
  }
  async function getColData() {
    const res = await listSdkDqDsTbCl({ tbId: tbid.value });
    console.log({ res11: res });
    permissionPrefix.value = `web:bu:form:curd:${tbid.value}`;

    const data = res.data; //.filter((item) => item.defaultShow);
    qFieldList.value = data.filter((item) => !item.pk && item.defaultShow);

    primaryKey.value = data.find((k) => k.pk)?.name ?? 'ID';

    console.log({ data });
    // 获取字典项
    await scanDict(data);
    // 拼接列表项
    genTableField(data);

    genFormField(data);
    getList.value = function () {
      // loading.value = true;
      // const formConditionList = getFormConditionList();
      // listItem(tableCode, pageParams.value, { formConditionList })
      //   .then((res) => {
      //     list.value = res?.data?.records ?? [];
      //     total.value = res?.data?.total ?? 0;
      //   })
      //   .finally(() => {
      //     loading.value = false;
      //   });
      loading.value = true;
      pageSdkDqSingleCurd(tbid.value, pageParams.value, queryParams.value)
        .then((res) => {
          console.log({ res22: res });
          list.value = res?.data?.records ?? [];
          total.value = res?.data?.total ?? 0;
        })
        .finally(() => {
          loading.value = false;
        });
    };

    reset.value = function () {
      form.value = { ...formParams.value };
    };

    cancel.value = function () {
      open.value = false;
      reset.value();
    };

    handleQuery.value = function () {
      pageParams.value.pageNum = 1;
      getList.value();
    };

    handleAdd.value = function () {
      reset.value();
      title.value = '新增';
      isDetail.value = false;
      open.value = true;
    };

    handleUpdate.value = function (row) {
      reset.value();
      const id = row?.[primaryKey.value] ?? ids.value?.[0];
      getSdkDqSingleCurdInfo(tbid.value, { [primaryKey.value]: id }).then((res) => {
        form.value = res.data;
        title.value = '修改';
        isDetail.value = false;
        open.value = true;
      });
    };
    handleDetail.value = function (row) {
      reset.value();
      const id = row?.[primaryKey.value] ?? ids.value?.[0];
      getSdkDqSingleCurdInfo(tbid.value, { [primaryKey.value]: id }).then((res) => {
        form.value = res.data;
        title.value = '修改';
        isDetail.value = true;
        open.value = true;
      });
    };

    submitForm.value = function () {
      if (form.value?.[primaryKey.value]) {
        updateSdkDqSingleCurd(tbid.value, form.value).then(() => {
          modal.msgSuccess('修改成功');
          open.value = false;
          getList.value();
        });
      } else {
        addSdkDqSingleCurd(tbid.value, form.value).then(() => {
          modal.msgSuccess('新增成功');
          open.value = false;
          getList.value();
        });
      }
    };

    handleDelete.value = function (row) {
      const idList = row?.[primaryKey.value] ? [row[primaryKey.value]] : ids.value;
      modal
        .confirm(`是否确认删除此数据项？`)
        .then(() => {
          return delSdkDqSingleCurd(tbid.value, idList);
        })
        .then(() => {
          getList.value();
          modal.msgSuccess('删除成功');
        });
    };

    getList.value();
  }
  // // 列表数据
  // function getList() {
  //   loading.value = true;
  //   pageSdkDqSingleCurd(tbid.value, pageParams.value, queryParams.value)
  //     .then((res) => {
  //       console.log({ res22: res });
  //       list.value = res?.data?.records ?? [];
  //       total.value = res?.data?.total ?? 0;
  //     })
  //     .finally(() => {
  //       loading.value = false;
  //     });
  // }
  async function useDict(...args) {
    const ans = {};
    for (const d of args) {
      ans[d] = (await getDicts(d)).data.map((p) => ({
        label: p.dictLabel,
        value: p.dictValue,
      }));
    }
    return ans;
  }
  async function scanDict(formCols) {
    const sysDictKey = formCols.filter((k) => k.dictType).map((k) => k.dictType);
    const sysDictOption = await useDict(...sysDictKey);

    dicts.value = {
      ...sysDictOption,
    };
  }
  function genTableField(formCols) {
    tableField.value = formCols
      .filter((k) => !k.pk && k.defaultShow)
      .map((k) => ({
        label: `${k.comment}(${k.name})`,
        prop: k.name,
        ext: k,
        ...(multiOptControlType.includes(k.inputType) && k.dictType
          ? {
              formatter: (row) => {
                return selectDictLabels(dicts.value[k.dictType] || [], row[k.name]);
              },
            }
          : {}),
      }));
  }

  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item[primaryKey.value]);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
  }
  // function handleQuery() {
  //   pageParams.value.pageNum = 1;
  //   getList();
  // }
  // function resetQuery() {
  //   queryRef.value?.resetFields();
  //   handleQuery();
  // }
</script>
<style lang="scss" scoped></style>
